//
//  SuaxinController.m
//  10.13
//
//  Created by M on 16/10/26.
//  Copyright © 2016年 apple1512. All rights reserved.
//

#import "SuaxinController.h"
#import "ListData.h"
#import "WaitCell.h"

@interface SuaxinController ()
{

    NSMutableArray<ListItemData *> *data;
    int page;
    BOOL finished;
}
//@property (weak, nonatomic) IBOutlet UIRefreshControl *refresh;

@end

@implementation SuaxinController

- (void)viewDidLoad {
    [super viewDidLoad];
    data = [NSMutableArray new];
    page = 1;
    finished = NO;
    
   }
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  data.count + 1;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row < data.count) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SSS" forIndexPath:indexPath];
        ListItemData *item = data[indexPath.row];
        cell.textLabel.text = item.name;
        cell.detailTextLabel.text = item.tel;
        return cell;
    
    }else{
        
        WaitCell *cell = (WaitCell *)[tableView dequeueReusableCellWithIdentifier:@"SSSS" forIndexPath:indexPath];
        if (finished) {
            [cell.av stopAnimating];
            cell.tipsLabel.text = @"没有更多数据了";
            return cell;
        }
        [cell.av startAnimating];
        cell.tipsLabel.text = @"";
        
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://xl18z.cn/list.php?page=%d",page++]];
        NSURLRequest *req = [NSURLRequest requestWithURL:url];
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask *task = [session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data_, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            // 获取到数据了。
            NSString *text = [[NSString alloc] initWithBytes:data_.bytes length:data_.length encoding:NSUTF8StringEncoding];
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data_ options:NSJSONReadingAllowFragments error:nil];
            ListData *d = [[ListData alloc] initWithDictionary:dict];
            [data addObjectsFromArray:d.record];
            NSLog(@"%@",text);
            // GCD 大中枢派发
            dispatch_async(dispatch_get_main_queue(), ^{
                // 刷新界面代码
                if (d.record.count < 10) {
                    finished = YES;
                }
                [tableView reloadData];
            });
        }];
        [task resume];
        
        return cell;
    }
    
    // Configure the cell...
    
    return nil;
}

@end
        
        



